package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.OrderMapper;
import com.jt.pojo.Order;
import com.jt.pojo.OrderDesc;
import com.jt.mapper.OrderDescMapper;
import com.jt.vo.OrderVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDescMapper orderDescMapper;

    @Override
    public PageResult getOrderList(PageResult pageResult) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(pageResult.getQuery()), "username", pageResult.getQuery());
        IPage<Order> page = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        page = orderMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();
        List<Order> rows = page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void createOrder(OrderVO orderVO) {
        Order order = orderVO.getOrder();
        orderMapper.insert(order);
        OrderDesc orderDesc = orderVO.getOrderDesc();
        orderDesc.setId(order.getId());
        orderDescMapper.insert(orderDesc);
    }

    @Override
    @Transactional
    public void deleteOrder(Integer id) {
        orderMapper.deleteById(id);
        orderDescMapper.deleteById(id);
    }

    @Override
    public void updateOrder(OrderVO orderVO) {
        Order order = orderVO.getOrder();
        orderMapper.updateById(order);
        OrderDesc orderDesc = orderVO.getOrderDesc();
        orderDescMapper.updateById(orderDesc);
    }


}
